﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Kingdee.SR.TD.PulgIn
{
    internal class KingdeeResutlHandler
    {
        //对ERP 返回进行统一 错误处理
        internal static void CheckList(List<List<object>> result)
        {
            //返回的数据类型为List<List<object>>，错误的返回结果只有一行数据且IsSuccess为False
            if (result.Count == 1)
            {
                //对返回结果进行解析和校验，这里使用的是JsonPatch
                var resultJObject = JArray.Parse(JsonConvert.SerializeObject(result[0]));
                var queryNode = resultJObject.SelectToken("$..IsSuccess");
                if (queryNode != null)
                {
                    if (!queryNode.Value<Boolean>())
                    {
                        var message = resultJObject.SelectToken("$...Message");
                        throw new Exception($"ERP接口调用错误：{message}");
                    }
                }

            }

        }

        internal static dynamic CheckObj(string resultJson)
        {
            var resultJObject = JObject.Parse(resultJson);
            var flag = resultJObject["Result"]["ResponseStatus"]["IsSuccess"].ToString();
            if (flag == "False")
            {
                var list = new List<string>();
                var errors = JArray.Parse(resultJObject["Result"]["ResponseStatus"]["Errors"].ToString());
                foreach (var item in errors)
                {
                    var mess = string.IsNullOrWhiteSpace(item["FieldName"].ToString())
                            ? item["Message"].ToString() : item["FieldName"].ToString() + "：" + item["Message"].ToString();
                    list.Add(mess);
                }
                var str = string.Join(";", list);
                throw new Exception(str);
            }
            else
            {
                return resultJObject["Result"]["Result"];
            }
        }

        internal static dynamic DeserialERPList(List<List<object>> list, string keys)
        {
            var res = new List<dynamic>();
            var keyList = keys.Split(',');
            foreach (var item in list)
            {
                var dic = new Dictionary<string, object>();
                var count = item.Count();
                for (int i = 0; i < count; i++)
                {
                    dic.Add(keyList[i], item[i]);
                }
                res.Add(dic);
            }
            return res;
        }
    }

}
